﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Ecobee.Net
{
	/// <summary>
	/// Represents a list of Thermostats with their revision numbers.
	/// </summary>
	public class SummaryRevisionList : ApiObjectCollection<SummaryRevision>
	{
		public SummaryRevisionList(Api api) : base(api)
		{
		}

		protected override void OnLoad(dynamic dataObject)
		{
			foreach (var item in dataObject)
			{
				// ***
				// *** Parse the string into its parts
				// ***
				string[] values = item.ToString().Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

				// ***
				// *** The parsed data will be assigned to a thermostat object
				// ***
				SummaryRevision summaryRevision = null;

				// ***
				// *** Check if the thermostat is already in the list
				// ***
				var existingItem = this.Where(t => t.Identifier == values[0]);

				if (existingItem.Count() == 1)
				{
					// ***
					// *** The thermostat already exists.
					// ***
					summaryRevision = existingItem.Single();
				}
				else
				{
					// ***
					// *** The thermostat does not exist. Create a new object
					// *** and add it to the collection.
					// ***
					summaryRevision = new SummaryRevision(this.Api);
					this.Add(summaryRevision);
				}

				// ***
				// *** Update the details
				// ***
				summaryRevision.Identifier = values[0];
				summaryRevision.Name = values[1];
				summaryRevision.Connected = Convert.ToBoolean(values[2]);
				summaryRevision.ThermostatRevision.SetNewValue(values[3]);
				summaryRevision.AlertsRevision.SetNewValue(values[4]);
				summaryRevision.RuntimeRevision.SetNewValue(values[5]);
			}
		}
	}
}
